package com.icangya.Utils;

import com.icangya.Utils.httpsRequest.MyX509TrustManager;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * Created by wang on 2017/4/10.
 */
public class HttpHelper {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static String doPost(String url, Map<String, Object> data) throws Exception {
        String result = "";
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.connect();
            JSONObject jsonObject = new JSONObject(data);
            StringBuffer queryBuffer = new StringBuffer();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                queryBuffer.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
            String queryStr = queryBuffer.substring(0, queryBuffer.length() - 1);
            queryStr = jsonObject.toString();
            System.out.println("请求支付的参数："+queryStr);
            PrintWriter writer = new PrintWriter(conn.getOutputStream());
            writer.write(queryStr);
            writer.flush();
            writer.close();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader((new InputStreamReader(inputStream)));
                String line;
                String str = "";
                StringBuffer buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    str += line;
                    buffer.append(line);
                }
                System.out.print(buffer.toString());

                return new String(buffer.toString().getBytes("GBK"), "UTF-8");
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }

    public static String doGet(String url, Map<String, Object> params, int type) throws Exception {
        String result = "";
        HttpURLConnection conn = null;
        try {
            StringBuffer queryBuffer = new StringBuffer();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                queryBuffer.append(entry.getKey() + "=" + URLEncoder.encode((String) entry.getValue(), "UTF-8") + "&");
            }
            String queryStr = queryBuffer.substring(0, queryBuffer.length() - 1);
            url = url + "?" + queryStr;
            System.out.println(url);
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0");
            conn.setReadTimeout(3000);
            conn.setConnectTimeout(3000);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null)
                result = result + line;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }



    public static String doMyPost(String url, Map<String, String> data) throws Exception {
        String result = "";
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            conn.connect();
            JSONObject jsonObject = new JSONObject(data);
//            StringBuffer queryBuffer = new StringBuffer();
//            for (Map.Entry<String, String> entry : data.entrySet()) {
//                queryBuffer.append(entry.getKey() + "=" + entry.getValue() + "&");
//            }
//            String queryStr = queryBuffer.substring(0, queryBuffer.length() - 1);
            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
//            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (data.get(k).trim().length() > 0) {// 参数值为空，则不参与签名
//                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                    jsonObject.put(k,data.get(k).trim());
                }
            }
//            String queryStr = sb.substring(0, sb.length() - 1);

            String queryStr = jsonObject.toString();
            System.out.println("请求支付的参数："+queryStr);
            PrintWriter writer = new PrintWriter(conn.getOutputStream());
            writer.write(queryStr);
            writer.flush();
            writer.close();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader((new InputStreamReader(inputStream)));
                String line;
                String str = "";
                StringBuffer buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    str += line;
                    buffer.append(line);
                }
                System.out.print(buffer.toString());

                return new String(buffer.toString().getBytes("GBK"), "UTF-8");
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }


    /*
 * 处理https GET/POST请求
 * 请求地址、请求方法、参数
 * */
    public static String httpsRequest(String requestUrl,String requestMethod,Map<String,String> data){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("TLS");
            TrustManager[] tm={new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);
//            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();

            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (data.get(k).trim().length() > 0) {// 参数值为空，则不参与签名
                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                }
            }
            String queryStr = sb.substring(0, sb.length() - 1);

            System.out.println("请求支付的参数："+queryStr);
            PrintWriter writer = new PrintWriter(conn.getOutputStream());
            writer.write(queryStr);
            writer.flush();
            writer.close();
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader((new InputStreamReader(inputStream)));
                String line;
                String str = "";
                buffer = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    str += line;
                    buffer.append(line);
                }
                System.out.print(buffer.toString());

                return new String(buffer.toString().getBytes("GBK"), "UTF-8");
            }

            //往服务器端写内容
//            if(null!=queryStr){
//                OutputStream os=conn.getOutputStream();
//                os.write(queryStr.getBytes("utf-8"));
//                os.close();
//            }

            //读取服务器端返回的内容
//            InputStream is=conn.getInputStream();
//            InputStreamReader isr=new InputStreamReader(is,"utf-8");
//            BufferedReader br=new BufferedReader(isr);
//            buffer=new StringBuffer();
//            String line=null;
//            while((line=br.readLine())!=null){
//                buffer.append(line);
//            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
